﻿package com.projects.xenia.documents_activities;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.projects.xenia.Activity_CustomersInfo;
import com.projects.xenia.Documents_Location;
import com.projects.xenia.MainCommentsActivity;
import com.projects.xenia.MainCustomersListActivity;
import com.projects.xenia.MainDebtsDetailsActivity;
import com.projects.xenia.R;
import com.projects.xenia.Documents_Location.GPSStateEnum;
import com.projects.xenia.R.id;
import com.projects.xenia.R.layout;
import com.projects.xenia.add_activities.Activity_InfoTabs;
import com.projects.xenia.documents_classes.Documents_Payment;
import com.projects.xenia.documents_classes.Documents_Visit;
import com.projects.xenia.global_modules.MainGlobalModule;
import com.projects.xenia.prompts_activities.Activity_NumericPrompt;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.LinearGradient;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class Activity_Payment extends Activity {
		
	private final Context Ctx = this;
	
	private Documents_Payment DocumentClass;
	
	private static final int IDD_PaymentDateDialog = 0;	
	private static final int IDD_PaymentAccTypeDialog = 1;
	private static final int IDD_PaymentFirmDialog = 2;	
	private static final int IDD_PaymentBaseListDialog = 3;
	
	private static final int IDR_CustomerSelect = 0;
	private static final int IDR_NoBaseSummSelect = 1;
	private static final int IDR_CommentsSelect = 2;
	private static final int IDR_BaseSelect = 3;
	private static final int IDR_BaseSummSelect = 4;	
	private final int IDR_GPSSettingsTest = 5;
	private final int IDR_MobileNetworkSettingsTest = 6;

	private ImageView _BackWard;

	
	private static ImageView PaymentGpsState; 
	
	private static Button PaymentDate;	
	
	private static Button PaymentCustomer;
	private static Button PaymentAccType;
	private static Button PaymentFirm;		
	private static Button PaymentComments;
	
	private static Cursor PaymentAccTypeCursor; 
	private static Cursor PaymentFirmCursor;
	
	private static TextView PaymentTotalPaymentSum;
	
	private static Button PaymentsBaseAddButton;
	
	private static ListView PaymentsBaseList;
	private static SimpleCursorAdapter PaymentsBaseAdapter;
	
	private static Cursor PaymentsBaseCursor;


    
	@Override
	protected void onDestroy() {
		super.onDestroy();
		MainGlobalModule.Documents_Location.StopLocation();
		MainGlobalModule.Documents_Location = null;
	}
	
	protected void GetPaymentsBaseCursor () {
		try {
			PaymentsBaseCursor = MainGlobalModule.DBE.rawQuery("select id as _id,* from xdoc_payments_t where hdoc_id = ? order by ddocdate", new String [] {DocumentClass.Head.id});	
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
	
	protected Cursor GetCursorByTable (String DB_TABLE) {
		return (MainGlobalModule.DBE.rawQuery("select id as _id, descr as descr from "+DB_TABLE+" order by descr", null));		
	}
	
	@Override
	public Object onRetainNonConfigurationInstance() {
		return (DocumentClass);
		
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
		
		if (MainGlobalModule.SettingsCollection.get("ManagerId").equals("")) {
			Toast xtoast = Toast.makeText(this, "Устройство не авторизовано !!!", 10);
			xtoast.show();
			finish();
		}
		
	
		if (!MainGlobalModule.CheckGPSSettings(false)) {			
			startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),IDR_GPSSettingsTest);
		}
		
		if (!MainGlobalModule.CheckMobileNetworkSettings()) {			
			startActivityForResult(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS),IDR_MobileNetworkSettingsTest);
		}
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);            
    	getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);        
    	setContentView(R.layout.payment_main_form);
    	
    	_BackWard = (ImageView)findViewById(R.id.BackwardButton);
    	_BackWard.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {				
				CloseDocument ();	
			}
		});
    	
    	
		Bundle DocExtras;
		DocExtras = getIntent().getExtras();			
	
		DocumentClass = (Documents_Payment) getLastNonConfigurationInstance();
		
		if (DocumentClass== null) { 
			DocumentClass = new Documents_Payment ();
			if (DocExtras!=null) {
				if (DocExtras.getString("DocId")!=null) {
					DocumentClass.OpenDoc(DocExtras.getString("DocId"));
					}
				else {
					DocumentClass.NewDoc();
					DocumentClass.Head.customers_id = DocExtras.getString("CustomerId");
					}
			}	
			else {
				DocumentClass.NewDoc();
			}	
		}
	
		PaymentGpsState = (ImageView) findViewById(R.id.PaymentGpsState);
		PaymentGpsState.setVisibility(View.INVISIBLE);
		
		if (MainGlobalModule.Documents_Location==null) {
			MainGlobalModule.Documents_Location = new Documents_Location();
			MainGlobalModule.Documents_Location.StartLocation(this, MainGlobalModule.DocumentsType.Payment, DocumentClass.Head.id,PaymentGpsState);
		}

		
    	PaymentDate = (Button) findViewById(R.id.PaymentDate);
    	//PaymentDate.setOnClickListener(PaymentDateDialog);
    	RefreshDate (PaymentDate,DocumentClass.Head.date_create);
    	
    	PaymentCustomer = (Button) findViewById(R.id.PaymentCustomer);
    	PaymentCustomer.setOnClickListener(PaymentCustomerSelect);
    	PaymentCustomer.setOnLongClickListener(CustomerLongSelect);    	
    	RefreshByCursor (PaymentCustomer , "xref_customers", DocumentClass.Head.customers_id);	
	
    	PaymentAccTypeCursor = GetCursorByTable ("xenum_AccType");
    	PaymentAccType = (Button) findViewById(R.id.PaymentAccType);
    	PaymentAccType.setOnClickListener(PaymentAccTypeDialog);
    	RefreshByCursor (PaymentAccType , "xenum_acctype", DocumentClass.Head.acctype);
	
    	PaymentFirmCursor = GetCursorByTable ("xref_firms");
    	PaymentFirm = (Button) findViewById(R.id.PaymentFirm);
    	PaymentFirm.setOnClickListener(PaymentFirmDialog);
    	RefreshByCursor (PaymentFirm , "xref_firms", DocumentClass.Head.firms_id);	

    	PaymentTotalPaymentSum = (TextView) findViewById(R.id.PaymentTotalPaymentSum);		
    	RefreshByDecimalValue (PaymentTotalPaymentSum,DocumentClass.Head.total_paymentsum);
    	PaymentTotalPaymentSum.setOnClickListener(PaymentTotalPaymentSum_Click);
	
    	PaymentComments = (Button) findViewById(R.id.PaymentCommentsButton);
    	PaymentComments.setOnClickListener(PaymentCommentsButton_Click);		
	
    	RefreshMultipleByCursor (PaymentComments,"xdoc_Payments_D");
    	
    	GetPaymentsBaseCursor ();    	
    	PaymentsBaseList = (ListView)findViewById(R.id.PaymentsBasesList);
    	
    	
    	try {
    		PaymentsBaseAdapter = new SimpleCursorAdapter(Ctx,R.layout.debtsdetails_form_list, PaymentsBaseCursor, new String [] {"dtypedoc_descr","ddocnum","ddocdate","dorder_sum","payment_sum"} , new int [] {R.id.DebtsDetailsDocType,R.id.DebtsDetailsDocNumber,R.id.DebtsDetailsDateDoc,R.id.DebtsDetailsSum,R.id.DebtsDetailsRestSum}); 
        	PaymentsBaseList.setAdapter(PaymentsBaseAdapter);        		
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	PaymentsBaseList.setOnItemLongClickListener(PaymentsBaseList_LongClick);
       	
    	PaymentsBaseAddButton = (Button)findViewById(R.id.PaymentsBasesAddButton);
    	PaymentsBaseAddButton.setOnClickListener(PaymentsBaseAddButton_Click);    	
    	
    	SetButtonsEnabled ();    	
    		
	}
	
	private OnLongClickListener CustomerLongSelect = new OnLongClickListener() {		
		@Override
		public boolean onLongClick(View v) {
			
			if (DocumentClass.Head.customers_id != null) {
				Intent InfoTabs = new Intent ();
				InfoTabs.setClass(Ctx,Activity_InfoTabs.class);			
				InfoTabs.putExtra("customer_id", DocumentClass.Head.customers_id);
				InfoTabs.putExtra("dayofroute",0);
				InfoTabs.putExtra("journaltab", false);
				startActivity(InfoTabs);
			}
			return true;
		}
	};
	
	private OnItemLongClickListener PaymentsBaseList_LongClick = new OnItemLongClickListener() {
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			
			showDialog(IDD_PaymentBaseListDialog);
			
			return false;
		}
	}; 
	
    boolean CustomerIsSelect () {    	
    	if (DocumentClass.Head.customers_id == null ) {
    		Toast.makeText(this, "Необходимо выбрать клиента !!!",Toast.LENGTH_LONG).show();
    		return false;	
    	}    		
    	return true;
    }
     
    
	private OnClickListener PaymentsBaseAddButton_Click = new OnClickListener() {		
		@Override
		public void onClick(View v) {			
			if (CustomerIsSelect()) {
				Intent DebtsDetails = new Intent();
				DebtsDetails.setClass(Ctx,MainDebtsDetailsActivity.class);			
				DebtsDetails.putExtra("Firm", DocumentClass.Head.firms_id);
				DebtsDetails.putExtra("AccType", DocumentClass.Head.acctype);
				DebtsDetails.putExtra("Customer", DocumentClass.Head.customers_id);			
				startActivityForResult(DebtsDetails, IDR_BaseSelect);	
			}
		}
	};
	
	private OnClickListener PaymentTotalPaymentSum_Click = new OnClickListener() {		
		@Override
		public void onClick(View v) {			
			if (CustomerIsSelect()) {    
				Intent NumericPad = new Intent();
				NumericPad.setClass(Ctx,Activity_NumericPrompt.class);
				NumericPad.putExtra("Numeric", DocumentClass.Head.total_paymentsum);
				startActivityForResult(NumericPad, IDR_NoBaseSummSelect);	
			}
		}
	};
	
	private OnClickListener PaymentCommentsButton_Click = new OnClickListener() {		
		@Override
		public void onClick(View v) {
					
			Intent Comments = new Intent();
			Comments.setClass(Ctx,MainCommentsActivity.class);
			Comments.putExtra("DocId",  DocumentClass.Head.id);
			Comments.putExtra("Destination_Table",  "xdoc_Payments_D");
			Comments.putExtra("Source_Table",  "xenum_PaymentNotes");
			startActivityForResult(Comments, IDR_CommentsSelect);			
			
		}
	};
	
	private void RefreshByDecimalValue (TextView DecimalTextView, Double DecimalValue) {
		
		DecimalTextView.setText(String.format("%.2f", DecimalValue));
		
	}
	
	private OnClickListener PaymentCustomerSelect= new OnClickListener () {	
		
		@Override
		public void onClick(View v) {
			
			Documents_Visit DocVisit = new Documents_Visit ();			 
			if (DocVisit.CheckOpenVisitsExistsByCustomerId(DocumentClass.Head.customers_id)) {
				Toast.makeText(Ctx, "Нельзя изменить клиента если есть открытый визит !", Toast.LENGTH_LONG).show();
			}
			else {
				Intent CustomerSelectintent = new Intent();
				CustomerSelectintent.setClass(Ctx,MainCustomersListActivity.class);
				CustomerSelectintent.putExtra("customer_id", DocumentClass.Head.customers_id);
				CustomerSelectintent.putExtra("customer_descr","");
	            startActivityForResult (CustomerSelectintent,IDR_CustomerSelect);	
			}						
		}
		
	};
	
	
	
	private void SetButtonsEnabled () {
		
		if (PaymentsBaseCursor.getCount()>0) {	
			
			PaymentTotalPaymentSum.setClickable(false);			
			PaymentCustomer.setClickable(false);
	    	PaymentAccType.setClickable(false);
	    	PaymentFirm.setClickable(false);			
		}
		
		else {
			
			PaymentTotalPaymentSum.setClickable(true);			
			PaymentCustomer.setClickable(true);
	    	PaymentAccType.setClickable(true);
	    	PaymentFirm.setClickable(true);			
		
		}			    	
    	
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {	
		
		try {
			
		 switch(requestCode) { 
		    case IDR_CustomerSelect:
		    	if (resultCode==RESULT_OK) {
		    		PaymentCustomer.setText(data.getStringExtra("customer_descr"));
		    		DocumentClass.Head.state = 1;
		    		DocumentClass.Head.customers_id = data.getStringExtra("customer_id");		    				    		
		    	}
		    	break;
		    case IDR_CommentsSelect:
		    	DocumentClass.Head.state = 1;
		    	RefreshMultipleByCursor (PaymentComments,"xdoc_Payments_D");
		    	break;
		    case IDR_NoBaseSummSelect:
		    	if  (data!=null) {
		    		DocumentClass.Head.state = 1;
		    		DocumentClass.Head.total_paymentsum = data.getDoubleExtra("NumericValue", DocumentClass.Head.total_paymentsum);
		    		DocumentClass.UpdateDoc();
		    		RefreshByDecimalValue(PaymentTotalPaymentSum, DocumentClass.Head.total_paymentsum);
		    	}
		    	break;
		    case IDR_BaseSelect:		    	
				
		    	if  (data!=null) {
		    		
			    	DocumentClass.Line.id = data.getStringExtra("id");
			    	DocumentClass.Line.hdoc_id = DocumentClass.Head.id;
			    	DocumentClass.Line.ddoc_id = data.getStringExtra("ddoc_id");
			    	DocumentClass.Line.dtypedoc_id = data.getStringExtra("dtypedoc_id");
			    	DocumentClass.Line.dtypedoc_descr = data.getStringExtra("dtypedoc_descr");
			    	DocumentClass.Line.ddocnum = data.getStringExtra("ddocnum");
			    	DocumentClass.Line.ddocdate = MainGlobalModule.sdf.parse(data.getStringExtra("ddocdate"));
			    	DocumentClass.Line.ddorder_sum = data.getDoubleExtra("dorder_sum",0);
			    	DocumentClass.Line.payment_sum = data.getDoubleExtra("dpayment_sum",0);
			    	
			    	Intent NumericPad = new Intent();
					NumericPad.setClass(Ctx,Activity_NumericPrompt.class);
					NumericPad.putExtra("Numeric", DocumentClass.Line.payment_sum);
					startActivityForResult(NumericPad,IDR_BaseSummSelect );
					
					DocumentClass.Head.state = 1;
					DocumentClass.UpdateDocLine();		    	
			    	RefreshByDecimalValue(PaymentTotalPaymentSum, DocumentClass.Head.total_paymentsum);
			    				    	
			    	PaymentsBaseAdapter.getCursor().requery();
			    	PaymentsBaseAdapter.notifyDataSetChanged();
			    	
			    	SetButtonsEnabled ();
		    		
		    	}		    	
		    	break;
		    	
		    	
		    case IDR_BaseSummSelect:		    	
				
		    	if  (data!=null) {
		    	
		    		DocumentClass.Head.state = 1;
		    		DocumentClass.Line.payment_sum = data.getDoubleExtra("NumericValue",0);
			    	DocumentClass.UpdateDocLine();
			    	
			    	RefreshByDecimalValue(PaymentTotalPaymentSum, DocumentClass.Head.total_paymentsum);		    	
			    	PaymentsBaseAdapter.getCursor().requery();
			    	PaymentsBaseAdapter.notifyDataSetChanged();	
		    	}
		    	
		    	SetButtonsEnabled ();
		    			    	
		    	break;
		    
		    case IDR_GPSSettingsTest:		    	
		    	if (!MainGlobalModule.CheckGPSSettings(false)) {			
		    		startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),IDR_GPSSettingsTest);
		    	}		    	
		    	break;
		    	
		    case IDR_MobileNetworkSettingsTest:
		    	if (!MainGlobalModule.CheckMobileNetworkSettings()) {
		    		startActivityForResult(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS),IDR_MobileNetworkSettingsTest);
		    	}
		    	break;
		    	
		 }
		 
		} catch (Exception e) {
			
			e.printStackTrace();
			
		} 
	   	
	};		
	
	private void RefreshDate (Button DateButton,Date DateValue) {
		SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy");
		DateButton.setText(sdf.format(DateValue));
	}	
	
	private void RefreshByCursor (Button SelectButton, String Table, String Id) {
		
		try {
			Cursor ScalarCursor = MainGlobalModule.DBE.query (Table, new String []{"descr"}, "id = ?", new String []{Id}, null, null, null);
			ScalarCursor.moveToFirst();
			SelectButton.setText(ScalarCursor.getString(0));
		} catch (Exception e) {
			SelectButton.setText ("");
		}		
	}
	
	private void RefreshMultipleByCursor (Button SelectButton, String Table) {
		
		String StringValues = "";
		try {
			Cursor ScalarCursor = MainGlobalModule.DBE.query (Table, new String []{"descr"}, "hdoc_id = ?", new String []{DocumentClass.Head.id},null,null,null);			
			while (ScalarCursor.moveToNext()){
				StringValues = StringValues.concat(ScalarCursor.getString(0))+","; 
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		SelectButton.setText(StringValues);
		
	}
	
	private OnClickListener PaymentDateDialog = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			showDialog(IDD_PaymentDateDialog);			
		}
	};

	private OnClickListener PaymentAccTypeDialog = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			showDialog(IDD_PaymentAccTypeDialog);			
		}
	};
	
	private OnClickListener PaymentFirmDialog = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			showDialog(IDD_PaymentFirmDialog);			
		}
	};
	
	@Override
	protected Dialog onCreateDialog(int id) {		
			
			super.onCreateDialog(id);
			
			int mYear;
			int mMonth;
			int mDay;
			
			Calendar C = Calendar.getInstance();
			
			AlertDialog.Builder adb = new AlertDialog.Builder(this);
			
			switch (id) {
			
			case IDD_PaymentDateDialog:
				C.setTime(DocumentClass.Head.date_create);
				mYear = C.get(Calendar.YEAR);
				mMonth = C.get(Calendar.MONTH);
				mDay = C.get(Calendar.DAY_OF_MONTH);			
				return new DatePickerDialog(this, PaymentDateSetListener, mYear, mMonth, mDay);
				
			case IDD_PaymentAccTypeDialog:
				adb.setTitle("Типы Учета");
				adb.setCursor(PaymentAccTypeCursor, PaymentAccTypeDialogClickListener , "descr");
				return adb.create();
				
			case IDD_PaymentFirmDialog:
				adb.setTitle("Фирмы");
				adb.setCursor(PaymentFirmCursor, PaymentFirmDialogClickListener , "descr");
				return adb.create();

			case IDD_PaymentBaseListDialog:
				adb.setItems(new String [] {"Удалить"} ,ActionSelectDialogListener);
				return adb.create();
								
			}
			
			
			return null;
			
		};
			
	private void DeleteBaseById (String lLineId) {
			
			DocumentClass.Line.id = lLineId;
			DocumentClass.DeleteDocLine ();
			PaymentsBaseAdapter.getCursor().requery();
	    	PaymentsBaseAdapter.notifyDataSetChanged();
	    	RefreshByDecimalValue(PaymentTotalPaymentSum, DocumentClass.Head.total_paymentsum);
	    	SetButtonsEnabled ();
	    	
		}
		
	private DialogInterface.OnClickListener ActionSelectDialogListener = new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int which) {
		    
		    	switch (which) {
	    		case 0:
	    			PaymentsBaseCursor.moveToPosition(which);
	    			DeleteBaseById (PaymentsBaseCursor.getString(0));
					break;	
		    	}
		  }		
		};		
		
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
		
		int mYear;
		int mMonth;
		int mDay;
		Calendar C = Calendar.getInstance();
		DatePickerDialog M;
		
		switch (id) {
		
		case IDD_PaymentDateDialog:		
			M = (DatePickerDialog)dialog;						
			C.setTime(DocumentClass.Head.date_create);		
			mYear = C.get(Calendar.YEAR);
			mMonth = C.get(Calendar.MONTH);
			mDay = C.get(Calendar.DAY_OF_MONTH);						
			M.updateDate(mYear, mMonth, mDay);
			break;	
			
			
			
		}		
		
	}
	
	private OnDateSetListener PaymentDateSetListener = new OnDateSetListener() {		
		@Override
		public void onDateSet(DatePicker view, int year, int month,int day) {						
			Calendar C = Calendar.getInstance();
			C.set(year, month, day);
			DocumentClass.Head.state = 1;
			DocumentClass.Head.date_create = C.getTime();
			RefreshDate (PaymentDate,DocumentClass.Head.date_create);
		}
	};	
		
	private DialogInterface.OnClickListener PaymentAccTypeDialogClickListener = new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
	    	PaymentAccTypeCursor.moveToPosition(which);
	    	PaymentAccType.setText(PaymentAccTypeCursor.getString(1));
	    	DocumentClass.Head.state = 1;
	    	DocumentClass.Head.acctype = PaymentAccTypeCursor.getString(0);	    	
	  }		
	};
	
	private DialogInterface.OnClickListener PaymentFirmDialogClickListener = new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
	    	PaymentFirmCursor.moveToPosition(which);
	    	PaymentFirm.setText(PaymentFirmCursor.getString(1));
	    	DocumentClass.Head.state = 1;
	    	DocumentClass.Head.firms_id = PaymentFirmCursor.getString(0);
	    }		
	  };
	
    public boolean onCreateOptionsMenu (Menu menu){    	
    	menu.add(Menu.NONE,1,Menu.NONE,"Записать");
    	menu.add(Menu.NONE,2,Menu.NONE,"Выход");
		return true;    	
    }
    
    public void FinishActivity () {
    	
    	DocumentClass.Head.state = 1;
    	DocumentClass.Head.verstamp++;
    	DocumentClass.UpdateDoc();
    	DocumentClass.FinishDoc ();
    	finish();    	
    	
    }
    
    
    private void CloseDocument () {
    	
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Закрытие документа");
		builder.setMessage("Сохранить изменения в документе ?");
		builder.setIcon(R.drawable.ic_achtung);
		builder.setPositiveButton("Да", new DialogInterface.OnClickListener() {    				    
			public void onClick(DialogInterface dialog, int which) {
				FinishActivity ();
		        dialog.dismiss();
		    }
		});

		builder.setNegativeButton("Нет", new DialogInterface.OnClickListener() {
		    @Override
		    public void onClick(DialogInterface dialog, int which) {
		    	
		    	if (DocumentClass.BackupIsExists()) {
		    		DocumentClass.RestoreDocument();
		    		finish();
		    	}
		    	else {
		    		DocumentClass.Head.customers_id = null;
		    		FinishActivity ();
		    	}		    	
		        dialog.dismiss();
		    }
		});

		builder.setNeutralButton("Отмена",new DialogInterface.OnClickListener() {			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				return;
			}
		}); 
		
		Dialog alert = builder.create();
		alert.show();  
		
    }
    
    
    public boolean onOptionsItemSelected (MenuItem item){
    	
    	switch (item.getItemId()) {
    	
    		case 1:
    			DocumentClass.Head.state = 1;
    			DocumentClass.UpdateDoc();    			
    			return true;
    			
    		case 2:
    			
    			CloseDocument ();
    			
    			return true;
    			
    		}    		
    			return false;    	
    	    
    }

    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {		
		
		switch (keyCode){
		
    		case KeyEvent.KEYCODE_BACK:    			
    			return false;   			
    		
    	}	
		return super.onKeyDown(keyCode, event);
	}
	
    
}
